<!--
  - Copyright (c) 2021.  北京维数科技有限公司
  - Date :  2021/3/25
  - Author ：F12 Console=> atob("MzMxNDkxODAwQHFxLmNvbQ==")
  - Version ：1.0.0
  -->

<template>
  <div>
    <div class="abstatic-height"></div>
    <div class="telnet-app-container">
      <el-row style="padding-bottom: 10px;">
        <el-button class="filter-item" type="primary" icon="edit" @click="handleCreate" size="mini">添加站点</el-button>
        <div class="search" style="float: right;">
          <span style="font-size: 14px;">站点</span>
          <el-input style="width: 200px;margin:0 10px;" class="filter-item" v-model="listQuery.name" size="mini">
          </el-input>
          <el-button class="filter-item" type="primary" icon="search" @click="searchsite" size="mini">查询</el-button>
        </div>
      </el-row>
      <el-main v-loading="listLoading" class="mainsitewrap">
        <el-scrollbar>
          <div class="tenet-list-row">
            <div v-for="(litem,index) in list" :key="index" class="tenet-list-col">
              <div :body-style="{ padding: '0'}" style="" class="tenet-list-wrap">
                <div class="img-card">
                  <img class="image" alt="暂无图片" :src="litem.attr2?litem.attr2:defaultsite">
                </div>
                <span class="title" :title="litem.name">{{litem.name}}</span>
                <span class="right-btn">
                  <el-button size="small" plain @click.stop="handleUpdate(litem.id)">
                    <icon-svg icon-class="bianji" style="fill:#50E3C2"/>
                  </el-button><br>
                  <el-button size="small" plain @click.stop="handleDelete(litem.id)">
                    <icon-svg icon-class="shanchu" style="fill:#50E3C2"/>
                  </el-button>
                </span>
              </div>
            </div>
          </div>
          <!--  <div class="card" v-for="(litem,index) in list" :key="index">
            <el-card :body-style="{ padding: '0'}" style="width: 100%;">
              <div class="img-card">
                 <img class="image" :src="litem.attr2?litem.attr2:defaultsite">
              </div>
                <span class="title" :title="litem.name">{{litem.name}}</span>
                <span class="right-btn">
                  <el-button size="small" plain  @click.stop="handleUpdate(litem.id)"><icon-svg icon-class="bianji" style="fill:#2683f5" />
                  </el-button>
                  <el-button size="small" plain @click.stop="handleDelete(litem.id)"><icon-svg icon-class="shanchu" style="fill:#2683f5" />
                  </el-button>
                </span>
            </el-card>
          </div> -->
          <div style="text-align: center;" v-if="nodata">
            <el-card>
              没有查询到该站点
            </el-card>
          </div>
        </el-scrollbar>
      </el-main>
      <el-footer>
        <el-pagination style="float:right;margin-top: 7px;" @size-change="handleSizeChange"
                       @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                       :page-sizes="[15,30,45, 60]"
                       :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </el-footer>
      <!--编辑,添加站点框 -->
      <slider-panel :Show.sync="dialogFormVisible" custom-class="out-side-frame">
        <div class="form-content-frame">
          <el-form :model="siteForm" label-position="top" :rules="rules" ref="siteForm" label-width="100px"
                   @submit.native.prevent>
            <el-form-item label="站点名" prop="sitename">
              <el-input v-model="siteForm.sitename"></el-input>
            </el-form-item>
            <el-form-item label="域名" prop="areaname">
              <el-input v-model="siteForm.areaname"></el-input>
            </el-form-item>
            <el-form-item label="上传logo（尺寸：60*60px 格式：png、jpg）">
              <span slot="label">上传logo（尺寸：60*60px&nbsp;&nbsp;&nbsp;&nbsp;格式：png、jpg）</span>
              <div v-show="siteForm.ImageUrl==''||siteForm.ImageUrl==undefined?false:true"><img class="uploadwrap"
                                                                                                :src="siteForm.ImageUrl==''||siteForm.ImageUrl==undefined?'':siteForm.ImageUrl"
                                                                                                alt=""
                                                                                                @click="triggerupload"/>
                <i class="el-icon-circle-close" style="position:absolute;margin: -8px 0 0 -5px;cursor: pointer;"
                   @click="delupimg"></i>
              </div>
              <el-upload action="" class="uploadwrap avatar-uploader" :beforeUpload="beforeUpload" :on-error="uploaderr"
                         accept="image/*" :http-request="uploadSectionFile"
                         v-show="siteForm.ImageUrl==''||siteForm.ImageUrl==undefined?true:false">
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- <img alt="" src="../../../assets/login-bg_images/logo.png"> -->
              <span class="tip" v-show="siteForm.ImageUrl==''||siteForm.ImageUrl==undefined?false:true">点击图标重新上传</span>
            </el-form-item>
            <el-form-item prop="username" label="用户名" class="username">
              <el-select v-model="siteForm.username" placeholder="请选择" style="width: 100%;">
                <el-option :label="item.username" :value="item.id" v-for="(item,index) in unbinduserlist" :key="index">
                  {{item.username}}
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 新增大屏地址与站点代号输入框 -->
            <el-form-item label="大屏地址" prop="site">
              <el-input v-model="siteForm.site"></el-input>
            </el-form-item>
            <el-form-item label="站点代号" prop="tenantNo">
              <el-input v-model="siteForm.tenantNo"></el-input>
            </el-form-item>
            <!-- end -->
            <el-form-item label="" prop="column" class="column">
              <span slot="label"><span style="color:red;">*</span> 站点栏目</span>
            </el-form-item>
            <div v-for="(item,index) in channellist" :key="index" class="editchannel">
              <el-input type="text" disabled="disabled" v-model="item.type"></el-input>
              <el-form-item class="checkbox" prop="columntype">
                <el-checkbox-group style="line-height: 25px;margin-top: 10px;" v-model="siteForm.columntype">
                  <el-checkbox :label="item1.id" name="type" @change="selchange" :checked="item1.isAdd==1?true:false"
                               v-for="(item1,index) in item.channels" :key="index">{{item1.channelName}}
                  </el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </div>
            <el-button v-if="textMap=='添加站点'" type="primary" @click="create('siteForm')" size="mini"
                       native-type="submit">确 定
            </el-button>
            <el-button v-else type="primary" @click="update('siteForm')" size="mini" native-type="submit">确 定
            </el-button>
            <el-button @click="cancel('siteForm')" type="text" size="mini">取 消</el-button>
          </el-form>
        </div>
      </slider-panel>

      <el-dialog title="删除站点" :visible.sync="isdelsite" :show-close='false' custom-class="xf-jc-dialog" width="360px"
                 height="160px">
        <div class="xf-jc-deletect">
          <p>{{delusertext}}</p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" size="mini" @click="delsite">删除</el-button>
          <el-button type="text" size="mini" @click="isdelsite=false">取消</el-button>
        </div>
      </el-dialog>

      <el-dialog title="取消提示" :visible.sync="iscancel" :show-close='false' custom-class="xf-jc-dialog" width="360px"
                 height="160px">
        <div class="xf-jc-deletect">
          <p>{{canceltext}}</p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="danger" size="mini" @click="cancelOk">确定</el-button>
          <el-button type="text" size="mini" @click="cancelNo">取消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
    import {randomn} from "@/utils";
    import {
        pageList,
        addObj,
        getObj,
        delObj,//删除
        putObj,//更新
        getUnbindUser,
        getSiteList,
        getOwner,//获取单个
    } from '@/api/admin/tenant/index';
    import {mapGetters} from 'vuex';
    import defaultimg from '@/assets/default-images/defaultsite.png';
    import {
        getToken
    } from '@/utils/auth';
    import sliderPanel from '@/components/SliderPanel'

    export default {
        name: 'tenant',
        components: {sliderPanel},
        data() {
            let mytoken = getToken();

            function isdns(rule, value, callback) {
                let reg = /^(?=^.{3,255}$)[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+$/;
                if (!reg.test(value) && value !== '') {
                    callback(new Error('请输入正确的域名格式!'))
                } else {
                    callback();
                }
            };
            return {
                listQuery: {
                    limit: 15,
                    name: "",
                    page: 1,
                },
                token: {"Authorization": mytoken},
                siteForm: {
                    sitename: '',
                    areaname: '',
                    ImageUrl: '',
                    uploadimgurl: '',
                    username: '',
                    site: '',
                    tenantNo: '',
                    columntype: [],
                },
                rules: {
                    sitename: [
                        {required: true, message: '请输入站点名', trigger: 'blur'},
                        {max: 100, message: '最多允许输入100个字符', trigger: 'blur'}
                    ],
                    areaname: [
                        {max: 100, message: '最多允许输入100个字符', trigger: 'blur'},
                        {validator: isdns, trigger: 'blur'}
                    ],
                    site: [
                        {required: true, message: '请输入大屏地址', trigger: 'blur'},
                        {type: 'url', message: '请输入正确的网址', trigger: ['blur', 'change']}
                    ],
                    tenantNo: [
                        {required: true, message: '请输入站点代号', trigger: 'blur'},
                        {max: 100, message: '最多允许输入100个字符', trigger: 'blur'}
                    ],
                    username: [
                        {required: true, message: '请选择用户名', trigger: 'change'},
                    ],
                    columntype: [
                        {required: true, message: '请选择站点栏目', trigger: 'change'},
                    ]
                },
                list: null,
                total: 0,
                dialogFormVisible: false,
                deviceMeasuringPointManager_btn_edit: false,
                deviceMeasuringPointManager_btn_del: false,
                deviceMeasuringPointManager_btn_add: false,
                textMap: "",
                isupload: false,
                delusertext: "删除站点会清空站点下的所有信息，确定删除吗？",
                isdelsite: false,
                iscancel: false,
                canceltext: "",
                defaultsite: defaultimg,
                uploadurl: "",
                unbinduserlist: [],
                channellist: [],
                updateid: "",
                listLoading: false,
                nodata: false
            }
        },
        created() {
            this.getList();
            this.getSites();
        },
        computed: {
            ...mapGetters([
                'elements'
            ])
        },
        methods: {
            getList() {
                this.listLoading = true;
                pageList(this.listQuery)
                    .then(response => {
                        if (response.data.rows.length == 0) {
                            this.nodata = true;
                        } else {
                            this.nodata = false;
                        }
                        this.list = response.data.rows;
                        this.total = response.data.total;
                        this.listLoading = false;
                    }).catch(() => {
                    this.listLoading = false
                })
            },
            // 获取用户名列表数据
            getUnbind(parms) {
                getUnbindUser(parms).then(response => {
                    this.unbinduserlist = response.data;
                })
            },
            getSites() {
                getSiteList().then(response => {
                    this.channellist = response.data;
                })
            },
            handleFilter() {
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.limit = val;
                this.getList();
            },
            // 重置表单
            resetsiteForm() {
                this.siteForm.sitename = "";
                this.siteForm.areaname = '';
                this.siteForm.ImageUrl = '';
                this.siteForm.uploadimgurl = '';
                this.siteForm.username = '';
                this.siteForm.site = '';
                this.siteForm.tenantNo = '';
                this.siteForm.columntype = [];
            },
            handleCreate() {
                this.resetsiteForm();
                this.textMap = '添加站点';
                this.canceltext = "确定取消添加站点？";
                this.siteForm.ImageUrl = "";
                this.siteForm.columntype = [];
                this.getUnbind();
                this.dialogFormVisible = true;
            },
            // 点击编辑按钮
            handleUpdate(data) {
                this.textMap = '编辑站点';
                this.canceltext = "确定取消编辑站点？";
                this.updateid = data;
                // 获取站点栏目各复选框的数据
                getSiteList({tenantId: data}).then(response => {
                    response.data.forEach((item, index) => {
                        item.channels.forEach((item1, index) => {
                            if (item1.isAdd == 1) {
                                this.siteForm.columntype.push(item1.id)
                            }
                        })
                    });
                });
                this.getUnbind({tenantId: this.updateid});
                getOwner(data).then(response => {
                    this.siteForm.sitename = response.data.tenant.name;
                    this.siteForm.areaname = response.data.tenant.attr1;
                    this.siteForm.ImageUrl = response.data.tenant.attr2;
                    this.siteForm.site = response.data.tenant.site;
                    this.siteForm.tenantNo = response.data.tenant.tenantNo;
                    if (response.data.user) {
                        if (this.unbinduserlist.length == 0) {
                            this.unbinduserlist = [];
                            this.unbinduserlist.push({
                                id: response.data.user.id,
                                username: response.data.user.username
                            });
                            this.siteForm.username = response.data.user.id;
                        } else {
                            this.unbinduserlist.forEach((item, index) => {
                                if (item.id != response.data.user.id) {
                                    this.unbinduserlist.push({
                                        id: response.data.user.id,
                                        username: response.data.user.username
                                    });
                                    this.siteForm.username = response.data.user.id;
                                    return;
                                } else {
                                    this.siteForm.username = response.data.user.id;
                                }
                            })
                        }
                    }
                    this.dialogFormVisible = true;
                }).catch(() => {
                    this.$notify({
                        title: '提示',
                        message: '网络错误！',
                        type: 'warning',
                        duration: 2000
                    });
                });
            },
            handleDelete(data) {
                this.updateid = data;
                this.isdelsite = true;
            },
            delsite() {
                let self = this;
                this.$prompt('', '删除确认', {
                    inputPlaceholder: "请输入超级管理员密码",
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputType: "password",
                    inputPattern: /^.{6,18}$/,
                    closeOnClickModal: false,
                    showClose: false,
                    closeOnPressEscape: false,
                    customClass: "confirmPassword",
                    cancelButtonClass: "cancelDel",
                    confirmButtonClass: "confirmDanger",
                    roundButton: true,
                    inputErrorMessage: '密码长度为6到18位字符串'
                }).then(({value}) => {
                    delObj({tenantId: this.updateid, superAdminPassword: window.btoa(window.btoa(value) + randomn(7))})
                        .then((res) => {
                            if (res.status == 200) {
                                self.isdelsite = false;
                                this.$notify({
                                    title: '成功',
                                    message: '删除成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                self.getList();
                            } else {
                                self.isdelsite = false;
                                this.$notify({
                                    title: '失败',
                                    message: res.message,
                                    type: 'warning',
                                    duration: 2000
                                });
                            }
                        });
                }).catch(() => {
                    self.isdelsite = false;
                });
            },
            // 新增保存
            create(formName) {
                let entity = {
                    name: this.siteForm.sitename,
                    attr1: this.siteForm.areaname,
                    attr2: this.siteForm.ImageUrl,
                    userId: this.siteForm.username,
                    site: this.siteForm.site,
                    tenantNo: this.siteForm.tenantNo,
                    channelIds: this.siteForm.columntype.toString()
                }
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        addObj(this.$qs.stringify(entity))//this.$qs.stringify(entity)
                            .then(() => {
                                this.dialogFormVisible = false;
                                this.getList();
                                this.resetsiteForm();
                                this.$notify({
                                    title: '成功',
                                    message: '创建成功',
                                    type: 'success',
                                    duration: 2000
                                });
                                set[formName].resetFields();
                            })
                    } else {
                        return false;
                    }
                });
            },
            cancel(formName) {
                this.iscancel = true;
            },
            // 更新保存
            update(formName) {
                let entity = {
                    tenantId: this.updateid,
                    name: this.siteForm.sitename,
                    attr1: this.siteForm.areaname,
                    attr2: this.siteForm.ImageUrl,
                    userId: this.siteForm.username,
                    site: this.siteForm.site,
                    tenantNo: this.siteForm.tenantNo,
                    channelIds: this.siteForm.columntype.toString()
                }
                const set = this.$refs;
                set[formName].validate(valid => {
                    if (valid) {
                        putObj(this.$qs.stringify(entity)).then(() => {
                            this.dialogFormVisible = false;
                            this.getList();
                            this.resetsiteForm();
                            this.$notify({
                                title: '成功',
                                message: '修改成功',
                                type: 'success',
                                duration: 2000
                            });
                            set[formName].resetFields();
                        });
                    } else {
                        return false;
                    }
                });
            },
            resetTemp() {
                this.form = {
                    username: undefined,
                    name: undefined,
                    sex: '男',
                    password: undefined,
                    description: undefined
                };
            },
            beforeUpload(file) {
                let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
                const extension = ["jpg", "png"].includes(testmsg);
                const is1M = file.size / 1024 / 1024 < 10;
                if (!extension) {
                    this.$notify({
                        message: "请上传正确的图片格式!",
                        type: "error",
                        duration: 2000
                    });
                }
                ;
                if (!is1M) {
                    this.$notify({
                        message: "上传图片大小不能超过 10MB!",
                        type: "error",
                        duration: 2000
                    });
                }
                this.isupload = true;
                return extension;
            },
            triggerupload() {
                document.querySelector(".el-upload__input").click();
            },
            uploadSectionFile: function (param) { //自定义文件上传
                this.uploadurl = "/api/device/deviceUploadInformation/save";
                let file = param.file;
                let self = this;
                let token = getToken();
                let FileController = this.uploadurl + "?fileName=" + file.name;
                let form = new FormData();
                form.append("file", file);
                let xhr = new XMLHttpRequest();
                xhr.open("post", FileController, true);
                xhr.setRequestHeader("Authorization", token);
                /*let reader = new FileReader();
              //获取base64编码
              reader.readAsDataURL(file);
              reader.onload = function(e) {
                curimgurl=e.target.result;
              };*/
                xhr.onload = function (res) {
                    if (res.currentTarget.status == 200) {
                        let imgurl = JSON.parse(res.currentTarget.response);
                        self.uploadsucces(imgurl.data.url);
                        self.isuploading = false;
                        self.$notify({
                            title: "成功",
                            message: "上传成功!",
                            type: "success",
                            duration: 2000
                        });
                    } else {
                        self.$notify({
                            title: "提示",
                            message: "上传失败!",
                            type: "warning",
                            duration: 2000
                        });
                    }
                };
                xhr.upload.onloadstart = function () {//上传开始执行方法
                    self.isuploading = true;
                };
                xhr.send(form);
            },
            uploadsucces(curimgurl) {
                this.siteForm.ImageUrl = curimgurl;
            },
            uploaderr(err, file, fileList) {
            },
            cancelOk() {
                this.iscancel = this.dialogFormVisible = false;
                this.$refs["siteForm"].resetFields();
            },
            cancelNo() {
                this.iscancel = false;
            },
            selchange(val) {
                if (true) {
                }
            },
            searchsite() {
                this.getList();
            },
            delupimg() {
                this.siteForm.ImageUrl = "";
            }
        }
    }
</script>

<style lang="scss" rel="stylesheet/scss">
  .telnet-app-container {
    padding: 20px;

    .filter-container {
      display: flex;
      justify-content: space-between;

      .title {
        color: rgb(129, 128, 128);
      }
    }

    .tenet-list-col {
      cursor: pointer;

      .img-card {
        height: 80px;
        width: 80px;
        // float: left;
        margin: 20px 0 20px 20px;
        display: inline-block;

        .image {
          width: 100%;
          height: 100%;
          border-radius: 3px;
          background-color: #ccc;
          vertical-align: middle;
        }
      }

      .right-btn {
        padding: 20px;

        .el-button:first-child {
          margin-bottom: 20px;
        }
      }
    }

    .title {
      font-size: 20px;
      width: calc(100% - 80px - 90px);
      margin: 20px 0 37px 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      word-break: break-all;
      color: rgba(255, 255, 255, 0.7);
    }

    .img-box {
      height: 60px;
      width: 60px;
      border: 1px solid #ccc;
      display: inline-block;
      text-align: center;
      line-height: 60px;
      cursor: pointer;

      .image {
        width: 100%;
        height: 100%;
        display: block;
      }
    }

    .el-dialog__footer {
      text-align: center;
    }

    .column {
      margin-bottom: 5px;
    }

    .tip {
      font-size: 12px;
      color: #666666;
      float: left;
      padding-top: 30px;
      height: 0;
      margin-left: 12px;
    }
  }

  .xf-query-input,
  .xf-query-select {
    width: 200px;
    margin: 0 10px;
  }

  .tenant-fulldialog > div {
    width: 500px;
    margin: 0 auto;
  }

  .tenant-fulldialog .el-dialog__title {
    font-size: 32px;
  }

  .tenant-fulldialog {
    .el-dialog__header {
      margin-top: 20px;
    }

    .custom-dialog-btn {
      position: absolute;
      font-size: 30px;
      left: 40px;
      top: 20px;
      color: #fff;

      &:hover {
        cursor: pointer;
      }
    }

    .dialog-footer {
      text-align: left;
    }
  }

  .editchannel .el-checkbox {
    margin: 0 25px 0 0;
  }

  .el-upload--picture-card {
    width: 60px;
    height: 60px;
    line-height: 60px;

    .el-icon-plus {
      line-height: inherit;
    }
  }

  .uploadwrap {
    width: 60px;
    height: 60px;
    line-height: 60px;
    float: left;
    cursor: pointer;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 100%;
    height: 100%;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    line-height: 60px;
    text-align: center;
  }

  .el-upload-list {
    display: none;
  }

  .mainsitewrap {
    padding: 0;
  }

  .mainsitewrap .el-scrollbar__wrap {
    overflow-x: hidden;
  }

  .mainsitewrap {
    @media screen and (max-width: 1440px) {
      .el-scrollbar {
        height: 75vh;
      }
    }
    @media screen and (min-width: 1441px) {
      .el-scrollbar {
        height: 80vh;
      }
    }
  }

  .confirmPassword {
    .el-message-box__btns {
      text-align: left;
    }

    .confirmDanger {
      float: left;
      margin-left: 0 !important;
      background: #f56c6c;
      border-color: #f56c6c;
      padding: 11px 22px;
    }

    .confirmDanger:hover {
      background: #f56c6c;
      border-color: #f56c6c;
    }

    .cancelDel {
      margin-left: 15px;
      padding: 11px 22px;
    }
  }

  .tenet-list-row {
    display: flex;
    flex-wrap: wrap;
  }

  .tenet-list-wrap {
    background: #0a1722;
    border-radius: 3px;
    border: 1px solid rgba(80, 227, 194, 0.3);
    width: 100%;
    display: flex;
    justify-content: space-between;
  }

  .tenet-list-col {
    width: calc(calc(100% - 110px) / 3);
    margin: 0 55px 55px 0;

    &:nth-child(3n) {
      margin-right: 0;
    }
  }
</style>

